const express = require('express')
const app = express()
const port = process.env.PORT || 10000

let usb = require('usb')
// let term = usb.findByIds(2385, 5734)  // U盘vId, pId
// term.open()
// console.log(term)
// if (term) {
//   // console.log('term', term)
//   term.open()
//   console.log(111, '是否进入')
//   var interface = term.interfaces[0]
//   interface.claim()
//   var inEndpoint = interface.endpoints[0]
//   var outEndpoint = interface.endpoints[1];

//   inEndpoint.transferType = 2;
//   inEndpoint.startStream(1, 64);
//   inEndpoint.transfer(64, function (error, data) {
//     if (!error) {
//         console.log(data);
//     } else {
//         console.log(error);
//     }
//   });
//   inEndpoint.on('data', function (data) {
//     console.log('接收数据', data);
//   });
//   inEndpoint.on('error', function (error) {
//     console.log(error);
//   });
//   outEndpoint.transferType = 2;
//   outEndpoint.startStream(1, 64);
//   outEndpoint.transfer(new Buffer('d\n'), function (err) {
//     console.log(err);
//   });
// }

var HID = require('node-hid')

// var SerialPort = require("serialport")


var usbDetect = require('usb-detection')
usbDetect.startMonitoring()


app.get('/', (req, res) => {
  res.setHeader('Access-Control-Allow-Origin','*');
	res.setHeader('Access-Control-Allow-Methods', 'GET, POST');  
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');  
  res.setHeader("Content-Type", "application/json;charset=utf-8"); 
  // var devices = HID.devices()
  var device = new HID.HID('/dev/hidraw0')
  res.send(device)

})

app.get('/usb', (req, res) => {
  res.send(usb.getDeviceList())
})

// app.get('/serialPortList', (req, res) => {
//   SerialPort.list().then(function (ports, err) {
//     res.send(ports)
//   })
// })

app.get('/Detection', (req, res) => {
  // usbDetect.find(2385, 5734, function (err, devices) {
  //   res.send(devices)
  // })
  // usbDetect.on('change', function (device) {
  //   res.send(device)
  // })
  usbDetect.find(function (err, devices) {
    res.send(devices)
  })
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})